package com.ytjj.qmyx.admin.service.impl;

import com.github.pagehelper.PageHelper;
import com.ytjj.common.api.CommonPage;
import com.ytjj.common.api.CommonResult;
import com.ytjj.common.api.ResultCode;
import com.ytjj.common.utils.OrderUtils;
import com.ytjj.qmyx.admin.dao.PhoneRechargeDao;
import com.ytjj.qmyx.admin.model.request.PhoneRechargeRequest;
import com.ytjj.qmyx.admin.model.response.PhoneRechargeResponse;
import com.ytjj.qmyx.admin.service.PhoneRechargeService;
import com.ytjj.qmyx.mall.client.MallClient;
import com.ytjj.qmyx.mall.model.PhoneRecharge;
import com.ytjj.qmyx.mall.model.ReturnPhoneRechargeRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 *
 * 
 * @Version: 1.0
 */
@Service
@Slf4j
public class PhoneRechargeServiceImpl implements PhoneRechargeService {

    @Resource
    private PhoneRechargeDao phoneRechargeDao;
    @Autowired
    private MallClient mallClient;

    @Override
    public CommonPage<PhoneRechargeResponse> getList(PhoneRechargeRequest phoneRechargeRequest) {
        PageHelper.startPage(phoneRechargeRequest.getPageNum(), phoneRechargeRequest.getPageSize());
        return CommonPage.restPage(phoneRechargeDao.getList(phoneRechargeRequest));
    }

    /**
     * 充值-退款
     * @return
     */
    @Override
    @Transactional
    public CommonResult returnPhoneRecharge(Integer id) {
        log.info("===returnPhoneRecharge.id==={}", id);
        if (null == id) {
            return CommonResult.failed(ResultCode.PHONE_RECHARGE_NOT_FOUND.getMessage());
        }
        PhoneRecharge phoneRecharge = phoneRechargeDao.getById(id);
        if (!phoneRecharge.getStatus().equals(3)) {
            return CommonResult.failed(ResultCode.PHONE_RECHARGE_STATUS_ERR.getMessage());
        }
        if (phoneRecharge.getRechargeStatus().equals(1)) {
            return CommonResult.failed(ResultCode.PHONE_RECHARGE_STATUS_SUCCESS.getMessage());
        }
        if (phoneRecharge.getRechargeStatus().equals(4)) {
            return CommonResult.failed(ResultCode.PHONE_RECHARGE_STATUS_DEAD.getMessage());
        }
        ReturnPhoneRechargeRequest request = new ReturnPhoneRechargeRequest(phoneRecharge.getType(), phoneRecharge.getOrderNo(), OrderUtils.getReturnCode(null), phoneRecharge.getPrice(), "平台退款");
        CommonResult result = mallClient.returnPhoneRecharge(request);
        if ("退款成功".equals(result.getData())) {
            phoneRecharge.setStatus(4);
            phoneRecharge.setRechargeStatus(4);
            phoneRechargeDao.updateByPhoneRecharge(phoneRecharge);
        }
        return result;
    }
}
